//
//  GoodAttributeEditVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/9/23.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "GoodAttributeEditVC.h"
#import "GoodAttributeListModel.h"
#import "GoodAttributeOneCell.h"
#import "GoodAttributeAddCell.h"
#import "ChooseGoodAttributeAlertView.h"

@interface GoodAttributeEditVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray <GoodAttributeOneModel *>*attributeArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation GoodAttributeEditVC

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - 64 - BottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
        [saveBtn setBackgroundColor:Color_ThemeColor];
        saveBtn.layer.masksToBounds = YES;
        saveBtn.layer.cornerRadius = 6;
        [saveBtn setTitle:@"保存" forState:0];
        [saveBtn setTitleColor:HexColor(0xffffff) forState:0];
        saveBtn.titleLabel.font = BoldFontOfSize(16);
        [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:saveBtn];
    }
    return _bottomView;
}

- (void)saveClick {
    [self requestForSave];
}

- (void)requestForSave {
    if (self.attributeArray.count) {
        NSMutableArray *mut = [NSMutableArray array];
        [self.attributeArray enumerateObjectsUsingBlock:^(GoodAttributeOneModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSMutableDictionary *dd = [NSMutableDictionary dictionary];
            [dd setObject:obj.name forKey:@"name"];
            [dd setObject:obj.currentValue forKey:@"value"];
            [dd setObject:obj.name_id forKey:@"name_id"];
            [dd setObject:obj.status forKey:@"status"];
            [dd setObject:self.n_id.length ? self.n_id : self.Id forKey:@"n_id"];
            [mut addObject:dd];
        }];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        if (self.n_id.length) {
            [dic setObject:self.n_id forKey:@"n_id"];
        }
        [dic setObject:[FactoryMethod toJSONString:mut] forKey:@"naturemodel"];
        [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerEditOtherGoodAttribute params:dic progress:^(NSProgress * _Nonnull progress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
            if (code) {
                [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"保存成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshGoodAttributeList object:nil];
                [self.rt_navigationController popViewControllerAnimated:YES];
            }
        } fail:^(NSError * _Nonnull error) {
            
        }];
    }else {
        [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"请添加属性"];
    }
}

-(NSMutableArray<GoodAttributeOneModel *> *)attributeArray {
    if (!_attributeArray) {
        _attributeArray = [NSMutableArray array];
    }
    return _attributeArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑属性模板";
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    [self requestForMuBanInfo];
}

- (void)requestForMuBanInfo {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (self.Id.length) {
        [dic setObject:self.Id forKey:@"id"];
    }
    if (self.n_id.length) {
        [dic setObject:self.n_id forKey:@"n_id"];
    }
    [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerGoodAttributeDetail params:dic progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.attributeArray = [GoodAttributeOneModel mj_objectArrayWithKeyValuesArray:responseObject];
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.attributeArray.count + 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.attributeArray.count) {
        GoodAttributeAddCell *cell = [GoodAttributeAddCell GoodAttributeAddCellWithTableView:tableView];
        __weak_self;
        cell.addBlock = ^{
            ChooseGoodAttributeAlertView *alert = [ChooseGoodAttributeAlertView new];
            alert.Id = weakself.Id;
            alert.n_id = weakself.n_id;
            alert.selectArray = weakself.attributeArray;
            alert.finishBlock = ^(GoodAttributeOneModel * _Nonnull model, BOOL isSelect) {
                if (model.isSelected) {
                    [weakself.attributeArray addObject:model];
                }else {
                    [weakself.attributeArray enumerateObjectsUsingBlock:^(GoodAttributeOneModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj.name_id isEqualToString:model.name_id]) {
                            if (stop) {
                                [weakself.attributeArray removeObject:obj];
                            }
                        }
                    }];
                }
                [tableView reloadData];
            };
            [alert showInView:MAIN_WINDOW];
        };
        return cell;
    }
    GoodAttributeOneCell *cell = [GoodAttributeOneCell GoodAttributeOneCellWithTableView:tableView];
    GoodAttributeOneModel *model = self.attributeArray[indexPath.row];
    cell.model = model;
    __weak_self;
    cell.clickBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [model.value enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                model.currentValue = obj;
                [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }];
            [alert addAction:action1];
        }];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:cancle];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.changeBlock = ^{
        if ([model.status isEqualToString:@"1"]) {
            model.status = @"2";
        }else {
            model.status = @"1";
        }
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    };
    cell.deleteBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定删除？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself.attributeArray removeObject:model];
            [tableView reloadData];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [self presentViewController:alert animated:YES completion:nil];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.attributeArray.count) {
        GoodAttributeAddCell *cell = [GoodAttributeAddCell GoodAttributeAddCellWithTableView:tableView];
        return cell.height;
    }
    GoodAttributeOneCell *cell = [GoodAttributeOneCell GoodAttributeOneCellWithTableView:tableView];
    return cell.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

@end
